package biz.core.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.io.IOUtils;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;


public class UploadAction implements ServletRequestAware, ServletResponseAware{

	private HttpServletRequest request;
    private HttpServletResponse response;

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
    }
	public String iframe()throws Exception{
		String result="";
		PrintWriter out= response.getWriter();
		try{
		 MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
		         // Bind allowed Files
		 		Map parameters=new HashMap<String, Object[]>();
		 		Map fileMessageMap=new HashMap<String, String>();
		 		String name="";
		 		String size="";
		         Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
		         while (fileParameterNames != null && fileParameterNames.hasMoreElements()) {
		             // get the value of this input tag
		             String inputName = (String) fileParameterNames.nextElement();
		             // get the content type
		             String[] contentType = multiWrapper.getContentTypes(inputName);
		                 // get the name of the file from the input tag
		                 String[] fileName = multiWrapper.getFileNames(inputName);
		                     // Get a File object for the uploaded File
		                     //这里这么就一下得到file了,看来是multiWrapper的问题
		                     File[] files = multiWrapper.getFiles(inputName);
		                     if (files != null) {
		                         for (int index = 0; index < files.length; index++) {
		                        	 File file=new File("D:",fileName[index]);
		                        	 write(files[index],file);
		                        	 name=fileName[index];
		                        	 size=files[index].length()+"";
		                        	 fileMessageMap.put("name", fileName[index]);
		                        	 fileMessageMap.put("size",files[index].length());
		                                parameters.put(inputName, files);
		                                parameters.put(inputName + "ContentType", contentType);
		                                parameters.put(inputName + "FileName", fileName);
		                         }
		                     }
		                 }
		         String jsonStr="{fileName:"+name+",size:"+size+"}";
		         jsonStr=name;
		        // jsonStr="<script> parent.callback('"+name+"')</script>";
		         result="<script> parent.callback('"+name+"')</script>";
		        //result="<script>parent.alert('abcd')</script>";
		        // jsonStr="abc";
		         //response.setContentType("text/html");
		         response.setContentType("text/html");
		        // out.println(result);
		         out.println(result);
		         }catch(Exception e){
		        	 out.println("<script type='text/javascript'>parent.alert('没有文件')</script>"); 
		         }
		         return null;
	}
	
	public String jQuery()throws Exception{
		String result="";
		PrintWriter out= response.getWriter();
		try{
		 MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
		         // Bind allowed Files
		 		Map parameters=new HashMap<String, Object[]>();
		 		Map fileMessageMap=new HashMap<String, String>();
		 		String name="";
		 		String size="";
		         Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
		         while (fileParameterNames != null && fileParameterNames.hasMoreElements()) {
		             // get the value of this input tag
		             String inputName = (String) fileParameterNames.nextElement();
		             // get the content type
		             String[] contentType = multiWrapper.getContentTypes(inputName);
		                 // get the name of the file from the input tag
		                 String[] fileName = multiWrapper.getFileNames(inputName);
		                     // Get a File object for the uploaded File
		                     //这里这么就一下得到file了,看来是multiWrapper的问题
		                     File[] files = multiWrapper.getFiles(inputName);
		                     if (files != null) {
		                         for (int index = 0; index < files.length; index++) {
		                        	 File file=new File("D:",fileName[index]);
		                        	 write(files[index],file);
		                        	 name=fileName[index];
		                        	 size=files[index].length()+"";
		                        	 fileMessageMap.put("name", fileName[index]);
		                        	 fileMessageMap.put("size",files[index].length());
		                                parameters.put(inputName, files);
		                                parameters.put(inputName + "ContentType", contentType);
		                                parameters.put(inputName + "FileName", fileName);
		                         }
		                     }
		                 }
		         String jsonStr="{fileName:"+name+",size:"+size+"}";
		         response.setContentType("text/html");
		         out.println(jsonStr);
		         }catch(Exception e){
		        	 out.println("<script type='text/javascript'>parent.alert('没有文件')</script>"); 
		         }
		         return null;
	}
	
	
	 public void write(File outputFile,File file) throws Exception {
	        // 自动创建目录
	        if (file != null) {
	            file.getParentFile().mkdirs();
	        }

            if (outputFile != null) {
                // Save the length of the file
                long size = outputFile.length();

                /*
                 * The uploaded file is being stored on disk
                 * in a temporary location so move it to the
                 * desired file.
                 */
                if (!outputFile.renameTo(file)) {
                    BufferedInputStream  in  = null;
                    BufferedOutputStream out = null;

                    try {
                        in  = new BufferedInputStream(new FileInputStream(outputFile));
                        out = new BufferedOutputStream(new FileOutputStream(file));
                        IOUtils.copy(in, out);
                    } finally {
                        if (in != null) {
                            try {
                                in.close();
                            } catch (IOException e) {
                                // ignore
                            }
                        }

                        if (out != null) {
                            try {
                                out.close();
                            } catch (IOException e) {
                                // ignore
                            }
                        }
                    }
                }
            } else {
                /*
                 * For whatever reason we cannot write the
                 * file to disk.
                 */
                throw new FileUploadException("Cannot write uploaded file to disk!");
            }
        
	    }


}
